package com.shuoyue.ycgk.ui.mine.info;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;

import com.bumptech.glide.Glide;
import com.shuoyue.ycgk.BuildConfig;
import com.shuoyue.ycgk.R;
import com.shuoyue.ycgk.appcatch.FileUtil;
import com.shuoyue.ycgk.appcatch.MemeryCatch;
import com.shuoyue.ycgk.appcatch.SPUtils;
import com.shuoyue.ycgk.apputis.XPermissionUtil;
import com.shuoyue.ycgk.base.BaseMvpActivity;
import com.shuoyue.ycgk.entity.UserInfo;
import com.shuoyue.ycgk.ui.account.ResetPwdActivity;
import com.shuoyue.ycgk.ui.account.UpdatePwdActivity;
import com.shuoyue.ycgk.ui.account.login.LoginActivity;
import com.shuoyue.ycgk.ui.common.UploadFileContract;
import com.shuoyue.ycgk.ui.shop.address.SelectAddressActivity;
import com.shuoyue.ycgk.utils.GlideUtil;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.yanzhenjie.album.Album;
import com.yanzhenjie.album.AlbumFile;
import com.yanzhenjie.album.api.widget.Widget;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import butterknife.BindView;
import butterknife.OnClick;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * 个人信息
 * Forty'7
 */
public class UserInfoActivity extends BaseMvpActivity<UpdateNickContract.Presenter>
        implements UploadFileContract.View, UpdateNickContract.View {

    @BindView(R.id.page_title)
    TextView tvTitle;
    @BindView(R.id.iv_head)
    ImageView ivHead;
    @BindView(R.id.tv_nickname)
    TextView tvNickname;
    XPermissionUtil xPermissionUtil;
    @BindView(R.id.back)
    ImageButton back;
    @BindView(R.id.iv_right)
    ImageView ivRight;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.l_right)
    FrameLayout lRight;
    @BindView(R.id.lay_head)
    LinearLayout layHead;
    @BindView(R.id.lay_nickname)
    LinearLayout layNickname;
    @BindView(R.id.layAddress)
    LinearLayout layAddress;
    @BindView(R.id.lay_setting)
    LinearLayout laySetting;
    @BindView(R.id.tv_out_lonin)
    TextView tvOutLonin;

    UploadFileContract.Presenter uploadFilePresenter;
    File soursFile;
    //    File tempFile;
    private Uri mImageUri;
    private Uri mSmallUri;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_user_info;
    }

    @Override
    protected void initView() {
        tvTitle.setText("个人信息");
        xPermissionUtil = new XPermissionUtil(this);
    }

    @Override
    public void initData() {
        super.initData();
        mPresenter = new UpdateNickContract.Presenter();
        mPresenter.attachView(this);
        uploadFilePresenter = new UploadFileContract.Presenter();
        uploadFilePresenter.attachView(this);
        if (SPUtils.getUserInfo(mContext) != null) {
            String photo = SPUtils.getUserInfo(mContext).getAvatar();
            GlideUtil.loadImageCircular(mContext,
                    photo,
                    R.mipmap.index_head,
                    ivHead);
            tvNickname.setText(SPUtils.getUserInfo(mContext).getUsername());
        }
    }


    @OnClick({R.id.back, R.id.lay_head, R.id.lay_nickname, R.id.lay_updatepwd, R.id.lay_resetpwd,
            R.id.tv_out_lonin, R.id.layAddress, R.id.lay_setting})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.lay_setting:
                startActivity(new Intent(mContext, SettingActivity.class));
                break;
            case R.id.back:
                finish();
                break;
            case R.id.layAddress:
                startActivity(new Intent(mContext, SelectAddressActivity.class));
                break;
            case R.id.lay_head:
                selectHeadPhoto();
                break;
            case R.id.lay_updatepwd:
                startActivity(new Intent(mContext, UpdatePwdActivity.class));
                break;
            case R.id.lay_resetpwd:
                startActivity(new Intent(mContext, ResetPwdActivity.class));
                break;
            case R.id.lay_nickname:
                Intent intent = new Intent(mContext, UpdateNickActivity.class);
                startActivity(intent);
                break;
            case R.id.tv_out_lonin:
                SPUtils.clearUserInfo(mContext);
                SPUtils.clearUserPassword(mContext);
                SPUtils.clearUserInfo(mContext);
                MemeryCatch.token = "";
//                startActivity(new Intent(mContext, LoginActivity.class));
                LoginActivity.start(mContext);
                UMShareAPI.get(mContext).deleteOauth(this, SHARE_MEDIA.WEIXIN, null);
                finish();
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 1001:
                    String nick = data.getStringExtra("nick");
                    tvNickname.setText(nick);
                    break;
                case 1046:
//                    Glide.with(mContext).load(tempFile)
//                            .error(R.mipmap.index_head)
//                            .placeholder(R.mipmap.index_head).into(ivHead);
//                    uploadFilePresenter.uploadFile(tempFile, "头像");

                    try {
                        if (mSmallUri != null) {
                            Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(mSmallUri));
//                            ivHead.setImageBitmap(bitmap);
                            Glide.with(mContext).load(bitmap)
                                    .error(R.mipmap.index_head)
                                    .placeholder(R.mipmap.index_head).into(ivHead);
                            uploadFilePresenter.uploadFile(new File(mSmallUri.getPath()), "头像");
                        } else {
                            Log.i("", "onActivityResult: Uri is null");
                        }
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                    break;
                default:
                    break;
            }
        }
    }

    private void selectHeadPhoto() {
        String[] permissions = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (EasyPermissions.hasPermissions(mContext, permissions)) {
            Album.image(mContext)
                    .singleChoice()
                    .columnCount(5)
                    .widget(Widget.newLightBuilder(mContext)
                            .statusBarColor(Color.WHITE).toolBarColor(Color.WHITE)
                            .navigationBarColor(Color.WHITE).build())
                    .onResult((ArrayList<AlbumFile> result) -> {
                        soursFile = new File(result.get(0).getPath());

//                        Glide.with(mContext).load(soursFile)
//                                .error(R.mipmap.index_head)
//                                .placeholder(R.mipmap.index_head).into(ivHead);
//                        uploadFilePresenter.uploadFile(soursFile, "头像");


                        //TODO
                        //下面代码是用来调用系统剪裁的
                        mImageUri = null;
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            mImageUri = FileProvider.getUriForFile(mContext, BuildConfig.APPLICATION_ID + ".FileProvider", soursFile);
                        } else {
                            mImageUri = Uri.fromFile(soursFile);
                        }
                        crop();
                    })
                    .start();

        } else {
            EasyPermissions.requestPermissions(UserInfoActivity.this, "需要获取您的相册、照相使用权限", 1, permissions);
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        xPermissionUtil.onRequestPermissionsResult(this, requestCode, grantResults);
    }


    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }

    @Override
    public void onUploadProgress(int progress, String... TAG) {

    }

    @Override
    public void onUploadSuc(String serverPath, String... TAG) {
        mPresenter.updateUserInfo(null, serverPath);
    }

    @Override
    public void onUploadFailed(String... TAG) {

    }

    @Override
    public void sucess(String nickName, String head) {
        UserInfo userInfo = SPUtils.getUserInfo(mContext);
        userInfo.setAvatar(head);
        SPUtils.updateUserInfo(mContext, userInfo);
        GlideUtil.loadImageCircular(mContext, head, R.mipmap.index_head, ivHead);

        toast("修改成功");
    }

    private void crop() {

        /*新建用于存剪裁后图片的文件，并转化为Uri*/
        File imageFile = createImageFile();
//        mSmallUri = Uri.fromFile(imageFile);
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//            mSmallUri = FileProvider.getUriForFile(mContext, BuildConfig.APPLICATION_ID + ".FileProvider", imageFile);
//        } else {
        mSmallUri = Uri.fromFile(imageFile);
//        }
        Log.i("==", "crop: " + mSmallUri);

        /*File image = new File(getExternalCacheDir() + "/demo.jpg");
        Log.i(TAG, "crop: path " + image.getAbsolutePath());
        mSmallUri = Uri.fromFile(image);*/

        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(mImageUri, "image/*");
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        intent.putExtra("crop", "true");
        intent.putExtra("scale", true);
        intent.putExtra("return-data", false);//设置为不返回缩略图
        intent.putExtra(MediaStore.EXTRA_OUTPUT, mSmallUri);//设置大图保存到文件
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());//保存的图片格式
        intent.putExtra("noFaceDetection", false);
        try {
            startActivityForResult(intent, 1046);
        } catch (Exception e) {
            Log.e("TAG____", e.getMessage());
        }
    }
//
//    /*缩略图*/
//    private void cropAndThumbnail() {
//        Intent intent = new Intent("com.android.camera.action.CROP");
//        intent.setDataAndType(mImageUri, "image/*");//设置要缩放的图片Uri和类型
//        intent.putExtra("aspectX", 768);//宽度比
//        intent.putExtra("aspectY", 1024);//高度比
//        intent.putExtra("outputX", 768);//输出图片的宽度
//        intent.putExtra("outputY", 1024);//输出图片的高度
//        intent.putExtra("scale", true);//缩放
//        intent.putExtra("return-data", false);//当为true的时候就返回缩略图，false就不返回，需要通过Uri
//        intent.putExtra("noFaceDetection", false);//前置摄像头
//
//        startActivityForResult(intent, 1046);
//    }

    /*用时间创建图片文件，防重名*/
    private File createImageFile() {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = new File(FileUtil.getPath(mContext) + "/catch/");
        if (!storageDir.exists()) {
            storageDir.mkdirs();
        }
        File imageFile = null;
        try {
            imageFile = File.createTempFile(imageFileName, ".jpg", storageDir);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return imageFile;
    }
}
